Debugging Python

There are several ways to debug Python.

This tutorial focuses on PDB, the debugger provided with Python.

Documentation for PDB is here: https://docs.python.org/3.5/library/pdb.html

You can run your Python script directly using the debugger:

$ python -m pdb script.py

Or interactively, for postmorten debugging:

>>> import pdb
>>> import script
>>> # here you call the code that crashes
>>> pdb.pm

Alternately you can insert the debugging into your script:

# start debugging your script here
import pdb
pdb.set_trace()

Once you are in the debugger it provides the following commands:

EOF    c          d        h         list      q        rv       undisplay
a      cl         debug    help      ll        quit     s        unt
alias  clear      disable  ignore    longlist  r        source   until
args   commands   display  interact  n         restart  step     up
b      condition  down     j         next      return   tbreak   w
break  cont       enable   jump      p         retval   u        whatis
bt     continue   exit     l         pp        run      unalias  where

You can access this list by typing: help

You can get more help on each command by typing: help <topic> for example: help list brings up:

l(ist) [first [,last] | .]

        List source code for the current file.  Without arguments,
        list 11 lines around the current line or continue the previous
        listing.  With . as argument, list 11 lines around the current
        line.  With one argument, list 11 lines starting at that line.
        With two arguments, list the given range; if the second
        argument is less than the first, it is a count.

        The current line in the current frame is indicated by "->".
        If an exception is being debugged, the line where the
        exception was originally raised or propagated is indicated by
        ">>", if it differs from the current line.

In everyday use you'll mainly need to know:

  • c or continue - Continues running the code
  • q or quit - Quits
  • l or list - Displays several lines around the current line or continue the previous listing.
  • s or step - Execute the current line, stop at the first possible occasion.
  • n or next - Continue execution until the next line in the current function is reached or it returns.
  • b or break - Set a breakpoint (depending on the argument provided).
  • r or return - Continue execution until the current function returns.
  • u or up - Move up the stack one frame.
  • d or down - Move down the stack one frame.
  • ! <code> - Evaluates the <code> as Python on the current frame
  • return or <enter> - Repeates the last command

and of course you can type and run and valid Python code so long as it's not a pdb command.


In [ ]:


In [ ]: